package com.anji.sp.push.service.impl;

import com.anji.sp.model.ResponseModel;
import com.anji.sp.push.model.MessageModel;
import com.anji.sp.push.model.po.PushConfiguresPO;
import com.anji.sp.push.model.vo.RequestSendBean;
import com.anji.sp.push.service.PushHistoryService;
import com.anji.sp.push.service.PushService;
import com.anji.sp.util.APPVersionCheckUtil;
import com.anji.sp.util.StringUtils;
import com.huawei.push.android.AndroidNotification;
import com.huawei.push.android.ClickAction;
import com.huawei.push.exception.HuaweiMesssagingException;
import com.huawei.push.message.AndroidConfig;
import com.huawei.push.message.Message;
import com.huawei.push.message.Notification;
import com.huawei.push.messaging.HuaweiApp;
import com.huawei.push.messaging.HuaweiCredential;
import com.huawei.push.messaging.HuaweiMessaging;
import com.huawei.push.messaging.HuaweiOption;
import com.huawei.push.model.Importance;
import com.huawei.push.model.Urgency;
import com.huawei.push.model.Visibility;
import com.huawei.push.reponse.SendResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 华为推送
 * </p>
 *
 * @author kean
 * @since 2021-01-20
 */
@Slf4j
@Service
public class HuaweiPushServiceImpl implements PushService {
    @Autowired
    private PushHistoryService pushHistoryService;
    @Autowired
    private JPushServiceImpl jPushService;

    /**
     * 批量推送
     *
     * @param requestSendBean
     * @param pushConfiguresPO
     * @param msgId
     * @param targetType
     * @return
     * @throws HuaweiMesssagingException
     */
    @Override
    public ResponseModel pushBatchMessage(RequestSendBean requestSendBean, PushConfiguresPO pushConfiguresPO, String msgId, String targetType) throws Exception {
        if (StringUtils.isEmpty(pushConfiguresPO.getHwAppId())
                || StringUtils.isEmpty(pushConfiguresPO.getHwAppSecret()) || StringUtils.isEmpty(pushConfiguresPO.getAppKey())) {
            //如果参数不全 那么走极光
            jPushService.pushAndroid(requestSendBean,pushConfiguresPO,msgId,"6",false);
            return ResponseModel.errorMsg("参数配置不全");
        }
        MessageModel messageModel = pushMessage(requestSendBean, pushConfiguresPO);
        if (messageModel.isSuccess()) {
            //保存历史数据
            ResponseModel responseModel = pushHistoryService.savePushHistory(requestSendBean, messageModel, msgId, targetType);
            return ResponseModel.success();
        }
        return ResponseModel.errorMsg(messageModel.getMessage());
    }

    /**
     * 全推送
     *
     * @param requestSendBean
     * @param pushConfiguresPO
     * @param msgId
     * @param targetType
     * @return
     * @throws HuaweiMesssagingException
     */
    @Override
    public ResponseModel pushAllMessage(RequestSendBean requestSendBean, PushConfiguresPO pushConfiguresPO, String msgId, String targetType) throws Exception {
        if (StringUtils.isEmpty(pushConfiguresPO.getHwAppId())
                || StringUtils.isEmpty(pushConfiguresPO.getHwAppSecret()) || StringUtils.isEmpty(pushConfiguresPO.getAppKey())) {
            //如果参数不全 那么走极光
            jPushService.pushAndroid(requestSendBean,pushConfiguresPO,msgId,"6",false);
            return ResponseModel.errorMsg("参数配置不全");
        }
        MessageModel messageModel;

        try {
            messageModel = pushMessage(requestSendBean, pushConfiguresPO);
        } catch (Exception e) {
            //发送失败重新尝试一次
            messageModel = pushMessage(requestSendBean, pushConfiguresPO);
        }
        //判断成功数是否是0
        if (APPVersionCheckUtil.strToInt(messageModel.getSuccessNum()) == 0){
            return jPushService.pushAndroid(requestSendBean, pushConfiguresPO, msgId, "6", false);
        }

        //保存历史数据
        return pushHistoryService.savePushHistory(requestSendBean, messageModel, msgId, targetType);
    }

    /**
     * 华为发送消息
     *
     * @param requestSendBean
     * @param pushConfiguresPO
     * @return
     * @throws HuaweiMesssagingException
     */
    private MessageModel pushMessage(RequestSendBean requestSendBean, PushConfiguresPO pushConfiguresPO) {
        try {
            //初始化华为客户端
            HuaweiCredential credential = HuaweiCredential.builder()
                    .setAppId(pushConfiguresPO.getHwAppId())
                    .setAppSecret(pushConfiguresPO.getHwAppSecret())
                    .build();

            // Create HuaweiOption
            HuaweiOption option = HuaweiOption.builder()
                    .setCredential(credential)
                    .build();
            HuaweiApp app = HuaweiApp.getInstance(option);
            HuaweiMessaging huaweiMessaging = HuaweiMessaging.getInstance(app);
            //配置通知信息
            Notification notification = Notification.builder().setTitle(requestSendBean.getTitle())
                    .setBody(requestSendBean.getContent())
                    .build();
            AndroidNotification androidNotification = AndroidNotification.builder().setIcon("/raw/ic_launcher2")
                    .setColor("#AACCDD")
                    .setDefaultSound(true)
                    .setClickAction(ClickAction.builder().setType(1).setAction("com.push.demo.internal").build())
                    .setStyle(1)
                    .setBigTitle(requestSendBean.getTitle())
                    .setBigBody(requestSendBean.getContent())
                    .setNotifyId(486)
                    .setImportance(Importance.LOW.getValue())
                    .setVisibility(Visibility.PUBLIC.getValue())
                    .setForegroundShow(true)
                    .build();
            AndroidConfig androidConfig;
            if (requestSendBean.getExtras() != null) {
                androidConfig = AndroidConfig.builder().setCollapseKey(-1)
                        .setUrgency(Urgency.HIGH.getValue())
                        .setTtl("10000s")
                        .setData(requestSendBean.getExtras().toString())
                        .setBiTag("the_sample_bi_tag_for_receipt_service")
                        .setNotification(androidNotification)
                        .build();
            } else {
                androidConfig = AndroidConfig.builder().setCollapseKey(-1)
                        .setUrgency(Urgency.HIGH.getValue())
                        .setTtl("10000s")
                        .setBiTag("the_sample_bi_tag_for_receipt_service")
                        .setNotification(androidNotification)
                        .build();
            }
            Message message = Message.builder().setNotification(notification)
                    .setAndroidConfig(androidConfig)
                    .addAllToken(requestSendBean.getTokens())
                    .build();
            SendResponse response = huaweiMessaging.sendMessage(message);
            jPushService.setPassThrougnMsg(requestSendBean, pushConfiguresPO);
            log.info("HuaweiPush.result {}", response);
            if (response.getCode().equals("80000000")) {//成功
                return MessageModel.success(requestSendBean.getTokens().size(), requestSendBean.getTokens().size(), "请求成功"+"\n");
            }else {
                return MessageModel.errorMsg(requestSendBean.getTokens().size(), 0, response.getMsg()+"\n");
            }
        } catch (Exception e) {
            log.error("HuaweiPush.pushMessage Exception .", e);
            return MessageModel.errorMsg(requestSendBean.getTokens().size(), 0, e.getMessage()+"\n");
        }
    }

}
